#include "stdafx.h"
#include <vector>
#include <memory>
#include "regionCounter.h"
#include "types.h"
#include <utility>

// direction vectors
static const int dx[] = { +1, 0, -1, 0 };
static const int dy[] = { 0, +1, 0, -1 };

static void dfs(Regions& mat, Labels& labels, int x, int y, int current_label) {
	// x and y are swapped
	if (x < 0 || x >= mat.size()) return; // out of bounds
	if (y < 0 || y >= mat.at(0).size()) return; // out of bounds
	if (mat[x][y].label != -1 || !mat[x][y].isText) return; // already labeled or not marked with 1 in m

	// mark the current cell
	mat[x][y].label = current_label;
	if (labels.size() == current_label){
		labels.push_back(std::vector<std::pair<unsigned int, unsigned int>>());
	}
	labels.at(current_label).push_back(std::pair<unsigned int, unsigned int>(x, y));

	// recursively mark the neighbors
	for (int direction = 0; direction < 4; ++direction)
		dfs(mat, labels, x + dx[direction], y + dy[direction], current_label);
}

Labels find_components(Regions& mat) {
	int component = 0;
	size_t sizeY = mat.size();
	size_t sizeX = mat.at(0).size();
	Labels  labels;
	for (int i = 0; i < sizeY; ++i){
		for (int j = 0; j < sizeX; ++j){
			if (mat[i][j].label == -1 && mat[i][j].isText)
				dfs(mat, labels, i, j, component++);
		}
	}
	return labels;
}